package com.m1905.lib.download.task;


import com.m1905.lib.download.model.DownloadDBItem;
import com.m1905.lib.download.request.StopException;

import java.util.List;

/**
 * @author wanghao
 * @date 2023/10/12.
 * @des
 */
public interface Interceptor {

    DownloadDBItem intercept(Chain chain);

    interface Chain {
        DownloadDBItem request();

        DownloadDBItem proceed(DownloadDBItem result) throws StopException;

    }

    class ApplicationInterceptorChain implements Chain {
        private int index;
        private DownloadDBItem request;
        private List<Interceptor> interceptors;

        public ApplicationInterceptorChain(int index, List<Interceptor> interceptors, DownloadDBItem request) {
            this.index = index;
            this.interceptors = interceptors;
            this.request = request;
        }

        @Override
        public DownloadDBItem request() {
            return request;
        }

        @Override
        public DownloadDBItem proceed(DownloadDBItem request) throws StopException {
            if (index < interceptors.size()) {
                Chain chain = new ApplicationInterceptorChain(index + 1, interceptors, request);
                return interceptors.get(index).intercept(chain);
            }
            return request;
        }
    }

}
